// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package config_cmd

import (
	"fmt"
	"os"
	"os/user"
	"syscall"

	"gitcode.com/opendragonfly/df_server/config"
	"gitcode.com/opendragonfly/df_server/utils"
	"github.com/spf13/cobra"
)

var removeRemoteCmd = &cobra.Command{
	Use: "removeRemote",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 1 {
			return fmt.Errorf("need param [remote id]")
		}
		return nil
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		//检查是否是root用户
		curUser, err := user.Current()
		if err != nil {
			return err
		}
		if curUser.Uid != "0" {
			return fmt.Errorf("need root to run this command")
		}

		remoteId := args[0]
		cfg, err := config.ReadServerConfig()
		if err != nil {
			return err
		}
		remoteList := []*config.RemoteConfig{}
		for _, remoteCfg := range cfg.RemoteList {
			if remoteCfg.RemoteId != remoteId {
				remoteList = append(remoteList, remoteCfg)
			}
		}
		cfg.RemoteList = remoteList
		err = config.WriteServerConfig(cfg)
		if err != nil {
			return err
		}
		fmt.Println("remove remote success")

		pid, err := utils.LoadPid()
		if err == nil {
			p, err := os.FindProcess(pid)
			if err == nil {
				p.Signal(syscall.SIGHUP)
				fmt.Println("send SIGHUP to process")
			}
		}

		return nil
	},
}
